$(function() {
    init();
    function init() {
        renderData();
        $(".searchBtn").on("tap",function () {
            var txt = $(".searchTxt").val();
            //判断用户输入是否正确
            if(!$.trim(txt)) {
                return;
            }
            var ls = localStorage;
            var arr = (ls.getItem("letaoHistory") && JSON.parse(ls.getItem("letaoHistory")))||[];
            //判断数组中是否已经存在有相同的数据
            for (var i = 0; i < arr.length; i++) {
                var element = arr[i];
                if(element==txt) {
                    // splice 删除已经存在了的数组(索引,要删除几个)
                    arr.splice(i,1);
                }
            }
            // unshift 从头部加一个数据
            arr.unshift(txt);
            ls.setItem("letaoHistory",JSON.stringify(arr));
            //页面跳转
            location.href = "./searchList.html?key="+txt;
        })
        $(".clearAll").on("tap",function() {
            localStorage.removeItem("letaoHistory");
        })
        $(".his_record ul").on("tap",".removeItem",function(e) {
            var aDom = e.target;
            var index = $(aDom).parent().data("index");
            var ls = localStorage;

            var arr = (ls.getItem("letaoHistory") && JSON.parse(ls.getItem("letaoHistory")))||[];
            arr.splice(index,1);
            var str = "";
            for (var i = 0; i < arr.length; i++) {
                var element = arr[i];
                str += '<li> '+ element+' <a data-index='+i+' class="removeItem mui-pull-right" href="javascript:;"><span class="mui-icon mui-icon-closeempty"></span></a></li>';
            }
            $(".his_record ul").html(str);
             // 数组存入本地存储中
            ls.setItem("letaoHistory",JSON.stringify(arr));
            
        })
    }

    function renderData() {
        var ls = localStorage;
        var arr = (ls.getItem("letaoHistory") && JSON.parse(ls.getItem("letaoHistory"))) || []; 

        var str="";
        for (var i = 0; i < arr.length; i++) {
            var element = arr[i];
            str += ' <li> ' + element + ' <a data-index=' + i + ' class="removeItem mui-pull-right" href="javascript:;"><span class="mui-icon mui-icon-closeempty"></span></a> </li>';
            
        }
        $(".his_record ul").html(str);

        if(arr.length>0) {
            $(".his_info").hide();
        }else {
            $(".his_record").hide();
        }
    }
});